import { defineStore } from 'pinia'
// 导入axios
import request from '@/utils/request'
import { IApiRes, profile } from '@/types/data'
// 数据持久化函数, 设置, 获取
import { getProfile, removeProfile, setProfile } from '@/utils/Profile'
import useCartStore from './cart'
// 应为只有汉字，所以给它添加一个id属性
export default defineStore('user', {
    // 数据持久化, 插件自动存储
    persist: {
        enabled: true
    },
    state: () => ({
        // 用户信息
        profile: getProfile() as profile,
    }),
    actions: {
        // 账号密码登录
        async login(from: { account: string, password: string }) {
            const { data: { result } } = await request.post<IApiRes<profile>>('/login', from)
            this.profile = result
            // 数据持久化
            setProfile(result)
        },

        // 手机号登录
        async mobileLogin(mobile: string, code: string) {
            const { data: { result } } = await request.post<IApiRes<profile>>('/login/code', {
                mobile,
                code
            })
            this.profile = result
        },

        // 请求验证码
        async sendMobileMsg(mobile: string) {
            await request.get('/login/code', {
                params: { mobile }
            })
        },

        // QQ第三方登录
        async loginQQ(openId: string) {
            const { data: { result } } = await request.post<IApiRes<profile>>('/login/social', {
                unionId: openId,
                source: 6
            })
            this.profile = result
            // 数据持久化
            setProfile(result)
        },

        // 绑定qq的短信验证码
        async sendQQBindMsg(mobile: string) {
            await request.get('/login/social/code', {
                params: {
                    mobile
                }
            })
        },

        // 立即绑定函数
        async qqBindLogin(openId: string, mobile: string, code: string) {
            const res = await request.post<IApiRes<profile>>('/login/social/bind', {
                mobile,
                code,
                unionId: openId
            })
            // 1. 保存用户信息到 state 中
            this.profile = res.data.result
            setProfile(res.data.result)
        },

        // 退出登录
        logout() {
            // (1) 清空pinia数据
            this.profile = {} as profile
            // (2) 清空本地数据
            removeProfile()
            // (3) 清空购物车
            const cart = useCartStore()
            // (4)
            sessionStorage.removeItem('cart')
            cart.clearCart()
        }
    },
    getters: {},

})